package com.zcb.rxjavapractice.api.service.impl;

import android.util.Log;

import com.zcb.rxjavapractice.api.ApiService;
import com.zcb.rxjavapractice.api.HttpResultSubscriber;
import com.zcb.rxjavapractice.api.ServiceFactory;
import com.zcb.rxjavapractice.bean.CloudccResult;
import com.zcb.rxjavapractice.api.service.CloudccService;
import com.zcb.rxjavapractice.bean.Yy;
import com.zcb.rxjavapractice.view.DemoView;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by admin on 2016/11/18.
 */

public class CloudccServiceImpl implements CloudccService{
    public static final String SignKey = "5cee621329f24e5cbdc43daa995ce9a1";

    public static final String sid="6ac0c53b128446b1b258ebef58075fce";//user id
    public static final String serviceName="cqueryWithRoleRight";
    public static final String objectApiName="fwdd";
    public static final String expressions="fwhg='a19201683A6D5A5n5SUH'";
    DemoView demoView;

    public CloudccServiceImpl(DemoView demoView) {
        this.demoView=demoView;
    }

    @Override
    public void sendVlidNum(String phone) {
        Map<String,String> map=new HashMap<String, String>();
        map.put("mobile", phone);
        sign(map);
        Observable observable= ServiceFactory
                .getInstance()
                .createService(ApiService.class)
                .sendValidNum(map);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpResultSubscriber<CloudccResult>() {
                    @Override
                    public void onSuccess(CloudccResult cloudccResult) {
                        String code=cloudccResult.code;

                        Log.d("zcb",cloudccResult.toString());
                    }

                    @Override
                    public void _onError(Throwable e) {
                        e.printStackTrace();
                    }
                });
    }


    @Override
    public void isValidNum(String phone,String num) {
        Map<String,String> map=new HashMap<String, String>();
        map.put("mobile", phone);
        map.put("code", num);
        sign(map);
        Observable observable= ServiceFactory
                .getInstance()
                .createService(ApiService.class)
                .isValidNum(map);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpResultSubscriber<CloudccResult>() {
                    @Override
                    public void onSuccess(CloudccResult cloudccResult) {
                        String code=cloudccResult.code;

                        Log.d("zcb",cloudccResult.toString());
                    }

                    @Override
                    public void _onError(Throwable e) {
                        e.printStackTrace();
                    }
                });

    }


    @Override
    public void login(String phone, String code) {
        Map<String,String> map=new HashMap<String, String>();
        map.put("mobile", phone);
        map.put("code", code);
        sign(map);
        Observable observable= ServiceFactory
                .getInstance()
                .createService(ApiService.class)
                .loginOn(map);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpResultSubscriber<CloudccResult>() {
                    @Override
                    public void onSuccess(CloudccResult cloudccResult) {
                        String code=cloudccResult.code;

                        Log.d("zcb",cloudccResult.toString());
                    }

                    @Override
                    public void _onError(Throwable e) {
                        e.printStackTrace();
                    }
                });
    }


    @Override
    public void queryCommon(String objectApiName,String expressions,String isAddDelete) {
        JSONObject json = new JSONObject();
        Map map = new TreeMap();

        try {
            json.put("serviceName","cquery");
            json.put("objectApiName",objectApiName);
            json.put("expressions",expressions);
            json.put("isAddDelete",isAddDelete);

            map.put("protocol", json.toString());
            map.put("sid", sid);
            sign(map);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Observable observable=ServiceFactory.getInstance()
                .createService(ApiService.class)
                .querycommon(map);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpResultSubscriber<CloudccResult>() {
                    @Override
                    public void onSuccess(CloudccResult cloudccResult) {
                        List list=cloudccResult.data.cloudcc.data;
                        System.out.println("length:"+list.size());
                        demoView.refreshList(list);
                    }

                    @Override
                    public void _onError(Throwable e) {

                    }
                });


    }


    /**
     * md5进行加密
     * @param param
     */
    private static void sign(Map<String, String> param)
    {
        param.put("seed", String.valueOf(System.currentTimeMillis()));
        Map<String, String> sort = new TreeMap(param);

        StringBuilder buf = new StringBuilder();
        String val = null;
        for (String key : sort.keySet())
        {
            val = sort.get(key);
            if (val != null)
            {
                buf.append(key).append("=").append(val).append("&");
            }
            else
            {
                param.remove(key);
            }
        }
        buf.append("key=").append(SignKey);

        System.out.println("签名前 " + buf.toString());
        String sign = MD5(buf.toString()).toLowerCase();
        System.out.println("签名后 " + sign);
        param.put("sign", sign);
    }


    /**
     * md5码加密
     * @param s
     * @return
     */
    private static String MD5(String s) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 把cloudcc返回的数据转化为需要的字符串
     * @param str
     */
    public static void cloudccToString(String str){
        try {
            JSONObject json=new JSONObject(str);
            String dataString=json.getString("data");
            JSONObject data=new JSONObject(dataString);

            JSONObject cloudcc=data.getJSONObject("cloudcc");
//			JSONArray dataArray=cloudcc.getJSONArray("data");
//			System.out.println("c长度："+dataArray.length());
//			System.out.println("字符串："+dataArray.toString());
            System.out.println("cloudcc："+cloudcc.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


}
